var request = require('request');

var token = {
    "accessToken" : null,
    "jsTicket" : null,
    "appId" : "wx56be4a588cb8e9e8",
    "AppSecret" : "c2062f00d5b144b4d2ba2b389ca4350b",
    "expiresIn" : null,
    get : function(){
        var that = this;

        request({
            method: 'get',
            uri: "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ that.appId +"&secret="+that.AppSecret
        }, function(err, req, body){
            if(err){
                return;
            };
            body = JSON.parse(body);
            if(body['access_token']){
                that.accessToken = body['access_token'];
                that.expiresIn = body['expires_in'] * 1000;
                that.jsget();
                setTimeout(function(){
                    that.get();
                }, that.expiresIn - that.expiresIn * .9);

            }else{
                console.log('error: '+ body.errmsg);
            }
        });
    },
    jsget : function(){
        var that = this;
        request({
            method: 'get',
            uri: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+ that.accessToken +'&type=jsapi'
        }, function(err, req, body){
            if(err){
                return;
            };
            body = JSON.parse(body);
            if(body['ticket']){
                that.jsTicket = body['ticket'];
            }else{
                console.log('error: '+ body.errmsg);
            }
        });
    }
};

module.exports = token;